<template>
  <div class="analytics-page">
    <h2 class="page-title">数据分析</h2>
    
    <el-row :gutter="20">
      <!-- 温度趋势图 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>温度趋势</span>
              <el-select
                v-model="selectedCity"
                placeholder="选择城市"
                size="small"
                clearable
              >
                <el-option
                  v-for="city in recordsStore.cities"
                  :key="city"
                  :label="city"
                  :value="city"
                />
              </el-select>
            </div>
          </template>
          <div ref="temperatureChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 天气分布图 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>天气分布</span>
          </template>
          <div ref="weatherChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 城市查询频率 -->
      <el-col :xs="24" :lg="12">
        <el-card class="chart-card">
          <template #header>
            <span>城市查询频率 TOP 10</span>
          </template>
          <div ref="cityChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <!-- 统计信息 -->
      <el-col :xs="24" :lg="12">
        <el-card class="stats-card">
          <template #header>
            <span>统计信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="总记录数">
              {{ recordsStore.records.length }}
            </el-descriptions-item>
            <el-descriptions-item label="城市数量">
              {{ recordsStore.cities.length }}
            </el-descriptions-item>
            <el-descriptions-item label="平均温度">
              {{ avgTemperature }}°C
            </el-descriptions-item>
            <el-descriptions-item label="平均湿度">
              {{ avgHumidity }}%
            </el-descriptions-item>
            <el-descriptions-item label="最高温度">
              {{ maxTemperature }}°C
            </el-descriptions-item>
            <el-descriptions-item label="最低温度">
              {{ minTemperature }}°C
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRecordsStore } from '@/stores/records'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { formatDate } from '@/utils/format'

const recordsStore = useRecordsStore()

// 图表实例
const temperatureChartRef = ref<HTMLElement>()
const weatherChartRef = ref<HTMLElement>()
const cityChartRef = ref<HTMLElement>()

let temperatureChart: ECharts | null = null
let weatherChart: ECharts | null = null
let cityChart: ECharts | null = null

// 选中的城市
const selectedCity = ref('')

// 统计数据
const avgTemperature = computed(() => {
  const records = recordsStore.records
  if (records.length === 0) return 0
  const sum = records.reduce((acc, r) => acc + r.temperature, 0)
  return (sum / records.length).toFixed(1)
})

const avgHumidity = computed(() => {
  const records = recordsStore.records
  if (records.length === 0) return 0
  const sum = records.reduce((acc, r) => acc + r.humidity, 0)
  return (sum / records.length).toFixed(1)
})

const maxTemperature = computed(() => {
  const records = recordsStore.records
  if (records.length === 0) return 0
  return Math.max(...records.map(r => r.temperature))
})

const minTemperature = computed(() => {
  const records = recordsStore.records
  if (records.length === 0) return 0
  return Math.min(...records.map(r => r.temperature))
})

// 初始化温度趋势图
const initTemperatureChart = () => {
  if (!temperatureChartRef.value) return
  
  temperatureChart = echarts.init(temperatureChartRef.value)
  updateTemperatureChart()
}

// 更新温度趋势图
const updateTemperatureChart = () => {
  if (!temperatureChart) return
  
  let records = recordsStore.records
  if (selectedCity.value) {
    records = records.filter(r => r.city === selectedCity.value)
  }
  
  // 按日期排序
  records.sort((a, b) => a.createdAt - b.createdAt)
  
  const option = {
    title: {
      text: selectedCity.value ? `${selectedCity.value} 温度趋势` : '温度趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: records.map(r => formatDate(r.createdAt))
    },
    yAxis: {
      type: 'value',
      name: '温度 (°C)'
    },
    series: [
      {
        name: '温度',
        type: 'line',
        data: records.map(r => r.temperature),
        smooth: true,
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  
  temperatureChart.setOption(option)
}

// 初始化天气分布图
const initWeatherChart = () => {
  if (!weatherChartRef.value) return
  
  weatherChart = echarts.init(weatherChartRef.value)
  
  // 统计天气类型
  const weatherCount: Record<string, number> = {}
  recordsStore.records.forEach(r => {
    weatherCount[r.weather] = (weatherCount[r.weather] || 0) + 1
  })
  
  const data = Object.entries(weatherCount).map(([name, value]) => ({
    name,
    value
  }))
  
  const option = {
    title: {
      text: '天气类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '天气类型',
        type: 'pie',
        radius: '50%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  weatherChart.setOption(option)
}

// 初始化城市查询频率图
const initCityChart = () => {
  if (!cityChartRef.value) return
  
  cityChart = echarts.init(cityChartRef.value)
  
  // 统计城市查询次数
  const cityCount: Record<string, number> = {}
  recordsStore.records.forEach(r => {
    cityCount[r.city] = (cityCount[r.city] || 0) + 1
  })
  
  // 排序并取前10
  const sortedCities = Object.entries(cityCount)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 10)
  
  const option = {
    title: {
      text: '城市查询频率',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: sortedCities.map(([city]) => city),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '查询次数'
    },
    series: [
      {
        name: '查询次数',
        type: 'bar',
        data: sortedCities.map(([, count]) => count),
        itemStyle: {
          color: '#67C23A'
        }
      }
    ]
  }
  
  cityChart.setOption(option)
}

// 初始化所有图表
const initCharts = async () => {
  await nextTick()
  initTemperatureChart()
  initWeatherChart()
  initCityChart()
}

// 监听城市选择变化
watch(selectedCity, () => {
  updateTemperatureChart()
})

// 监听记录变化
watch(() => recordsStore.records.length, () => {
  updateTemperatureChart()
  initWeatherChart()
  initCityChart()
})

// 处理窗口大小变化
const handleResize = () => {
  temperatureChart?.resize()
  weatherChart?.resize()
  cityChart?.resize()
}

onMounted(() => {
  initCharts()
  window.addEventListener('resize', handleResize)
})

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  temperatureChart?.dispose()
  weatherChart?.dispose()
  cityChart?.dispose()
})
</script>

<style lang="scss" scoped>
.analytics-page {
  padding: 20px;
  
  .page-title {
    font-size: 24px;
    margin-bottom: 20px;
  }
  
  .chart-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .chart-container {
      height: 400px;
    }
  }
  
  .stats-card {
    margin-bottom: 20px;
    height: 100%;
  }
}
</style> 